using AutoMapper;
using B.S.NewMedical.Api.Read.Application.Command.Doctor.Checkup;
using B.S.NewMedical.Api.Read.DTOS.Checkup;
using B.S.NewMedical.Domain.Doctor;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.Doctor.Checkup
{
    /// <summary>
    /// 获取检查项目列表处理器
    /// </summary>
    public class GetCheckupItemsHandler : IRequestHandler<GetCheckupItemsCommand, ApiResult<List<CheckupItemDto>>>
    {
        private readonly IBaseRepository<CheckupItemModel> _checkupItemRepository;
        private readonly IBaseRepository<CheckupCategoryModel> _categoryRepository;
        private readonly ILogger<GetCheckupItemsHandler> _logger;
        private readonly IMapper _mapper;

        public GetCheckupItemsHandler(
            IBaseRepository<CheckupItemModel> checkupItemRepository,
            IBaseRepository<CheckupCategoryModel> categoryRepository,
            ILogger<GetCheckupItemsHandler> logger,
            IMapper mapper)
        {
            _checkupItemRepository = checkupItemRepository;
            _categoryRepository = categoryRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult<List<CheckupItemDto>>> Handle(GetCheckupItemsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取检查项目列表，分类ID：{CategoryId}", request.CategoryId);

                var query = _checkupItemRepository.GetAll().Where(c => !c.IsDeleted);

                // 按分类筛选
                if (request.CategoryId.HasValue)
                {
                    query = query.Where(c => c.CategoryId == request.CategoryId.Value);
                }

                var checkupItems = await query.ToListAsync(cancellationToken);
                var categories = await _categoryRepository.GetAll().Where(c => !c.IsDeleted).ToListAsync(cancellationToken);

                // 手动映射并添加分类名称
                var result = checkupItems.Select(item => new CheckupItemDto
                {
                    Id = item.Id,
                    CategoryId = item.CategoryId,
                    CategoryName = categories.FirstOrDefault(c => c.Id == item.CategoryId)?.CategoryName ?? "未知分类",
                    ItemName = item.ItemName,
                    Price = item.Price,
                    Notes = item.Notes
                }).ToList();

                return new ApiResult<List<CheckupItemDto>>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取检查项目列表成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取检查项目列表时发生异常");
                return new ApiResult<List<CheckupItemDto>>
                {
                    Code = ApiEnum.Error,
                    Msg = "获取检查项目列表失败：" + ex.Message
                };
            }
        }
    }
}